package com.shuqi.activity;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shuqi.activity.adapter.BookShelfAdapter;
import com.shuqi.activity.viewport.BookShelfTitle;
import com.shuqi.activity.viewport.BottomDialog;
import com.shuqi.activity.viewport.CustomPopupWindow;
import com.shuqi.activity.viewport.UpdateDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.bookbag.BookBagDao;
import com.shuqi.common.CheckBookMarkUpdate;
import com.shuqi.common.CheckBookMarkUpdate.CheckBookMarkUpdateLinstener;
import com.shuqi.common.CheckUser;
import com.shuqi.common.Config;
import com.shuqi.common.EnterBookContent;
import com.shuqi.common.FunctionsSwitch;
import com.shuqi.common.MyTask;
import com.shuqi.common.NetNotify;
import com.shuqi.common.RedDotProvider;
import com.shuqi.common.SyncBookMarks;
import com.shuqi.common.SyncBookMarks.SyncBookMarksResultToUILinstener;
import com.shuqi.common.Urls;
import com.shuqi.common.ViewHelpProvider;
import com.shuqi.common.ViewHelpProvider.ViewHelpHandleType;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.MyUrlTools;
import com.shuqi.common.utils.SharedPreferenceUtil;
import com.shuqi.common.utils.StringUtils;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookCataLogDao;
import com.shuqi.database.dao.impl.BookMarkInfoDao;
import com.shuqi.database.dao.impl.VersionShowDao.VersionShowEnum;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.database.model.UserInfo;
import com.shuqi.download.database.DownloadInfo;
import com.shuqi.download.listener.DownloadStateListener;
import com.shuqi.download.util.DownloadStatus;
import com.shuqi.interfaces.CheckUserListener;
import com.shuqi.model.bean.CheckBookUpdateInfo;
import com.shuqi.model.bean.SoftUpdateInfo;
import com.shuqi.model.manager.BookMarkManager;
import com.shuqi.model.manager.DownLoadBookManager;
import com.shuqi.model.manager.DownLoadShuqiBook;
import com.shuqi.model.manager.DownLoadShuqiBook.StartDownBookListener;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.manager.SoftCofigManager;
import com.shuqi.model.manager.TxtDownLoadManager;
import com.shuqi.model.net.HttpFactory;
import com.shuqi.service.UpdateService;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 书架
 * 
 * @author Jianda.Yang
 * 
 * @Date 2014-1-16 下午8:23:31
 */
public class BookShelfActivity extends ActivityBase implements OnClickListener,
        DownloadStateListener, OnItemClickListener, OnItemLongClickListener {

    /** 所需常量，标志 */
    private static final String TAG = "BookShelfActivity";
    public final static String INTENT_FROM_FILE = "filePath";
    public final static String INTENT_SHOWGUIDE = "showGuide";
    public static final int SHOW_UPDATE = 100; // 更新
    public static final int HIDE_ADDBOOK_DIALOG = 200;
    private boolean isCanQuit = false;

    private BookShelfTitle mTitle;
    public GridView mGridView;

    /** 增加书籍底部框 */
    private BottomDialog dialogAddBook;
    private RelativeLayout tvHotBookRecommen;// 热书推荐
    private RelativeLayout tvLocalLoad1;// 底部导入本地
    private RelativeLayout tvWifiTransfer1;// 底部wifi传书

    /** 更多功能popwindow */
    private CustomPopupWindow popDialogMore;
    private TextView tvPersonalCenter;// 个人中心
    private TextView tvLocalLoad;// 导入本地
    private TextView tvBookManagement;// 书籍管理
    private TextView tvOfflineMangement;// 离线管理
    private TextView tvMyBookBag;// 我的书包
    private View tvMyBookBag_line;// 我的书包线
    private TextView tvFeedBack;// 意见反馈

    /** 删除书籍底部框 */
    private BottomDialog dialogDel;
    private TextView tvDelTitle;// 对话框中的删除title
    private TextView tvSelCancel;// 删除对话框中的取消按钮
    private TextView tvDel;// 对话框中的删除按钮
    private TextView tvDelDialogDisInfo = null;// 删除提示
    private CheckBox delFileBox;// 多选框
    private boolean isDelFile = true;// 删除物理文件标记

    /** 编辑底部导航 */
    /** 删除状态下删除选择图片的切换标记 */
    public HashMap<String, BookMarkInfo> mDelBookMap = new HashMap<String, BookMarkInfo>();
    private LinearLayout mBottomLinearLayout;
    private TextView tvCancel;// 取消
    private TextView tvDelSel;// 删除所选项
    public boolean isRedact = false;// 是否是编辑状态

    /** 软件更新对话框 */
    private UpdateDialog dialog;

    /** 2G/3G 网络提示dialog */
    private Dialog mNetworkDialog;
    private View mNetWorkConfirmView;// 网络提示 确认按钮

    /** 书签数据 */
    List<BookMarkInfo> liMarkInfos; // 数据源
    private BookShelfAdapter bkShelfAdapter;
    private SyncBookMarksListener syncListener;
    private CheckUpdateBookMarksListener checkUpdateListener;

    private PopupWindow viewHelp;
    /** 定时任务 */
    private Timer timer = new Timer();

    /** 延时显示更新对话框 */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case SHOW_UPDATE:
                    dialog.show();
                    break;
                case HIDE_ADDBOOK_DIALOG:
                    hideAddBookDialog();
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_bookshelf);
        init();
        jumpToBookContent();
        // jumpToNewGuide();//8.0.1 此处废弃，迁移到Loading
        // 同步云书签
        syncBookMark("yes");

    }

    // @Override
    // public void onAttachedToWindow() {
    // super.onAttachedToWindow();
    //
    // View parentView = findViewById(R.id.bookshelf_root);
    // int resId = R.layout.view_help_bookshelf;
    // VersionShowEnum vShowEnum = VersionShowEnum.view_help_bookshelf;
    //
    // ViewHelpProvider.getInstance().handle(this, vShowEnum,ViewHelpHandleType.layout, parentView,
    // resId);
    // }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        if (viewHelp == null || !viewHelp.isShowing()) {// 当前没有显示帮助界面时执行
            View parentView = findViewById(R.id.bookshelf_root);
            int resId = R.layout.view_help_bookshelf;
            VersionShowEnum vShowEnum = VersionShowEnum.view_help_bookshelf;

            viewHelp =
                    ViewHelpProvider.getInstance().handle(this, vShowEnum,
                            ViewHelpHandleType.layout, parentView, resId);
        }

        if (hasFocus) {// 延迟绑定事件,100毫秒
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    mTitle.setImageListener(BookShelfActivity.this);
                }
            }, TimeUnit.MILLISECONDS.toMillis(200));

        } else {// 解绑事件
            mTitle.setImageListener(null);

        }

    }

    @Override
    protected void onStop() {
        super.onStop();

        if (viewHelp != null && viewHelp.isShowing())
            viewHelp.dismiss();
        if (popDialogMore != null && popDialogMore.isShowing())
            popDialogMore.dismiss();
    }


    private void init() {
        mTitle = (BookShelfTitle) findViewById(R.id.title);

        tvCancel = (TextView) findViewById(R.id.shelf_cancel_tv);
        tvDelSel = (TextView) findViewById(R.id.shelf_del_sel_tv);
        tvCancel.setOnClickListener(this);
        tvDelSel.setOnClickListener(this);

        mGridView = (GridView) findViewById(R.id.bookshelf_main_gridview);
        mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        bkShelfAdapter = new BookShelfAdapter(this);
        mGridView.setAdapter(bkShelfAdapter);
        mGridView.setOnItemClickListener(this);
        mGridView.setOnItemLongClickListener(this);
        mGridView.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
                    mGridView.clearFocus();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {}
        });

        checkShuqiUpdate();
    }


    @Override
    protected void onResume() {
        super.onResume();
        loadData();
        StatisticsUtils.onEvent(this, StatisticsEventID.BOOKSHELF_BOOKSHELF_7_3_8);
    }

    @Override
    public void activityLogicForward() {}

    @Override
    public void activityInitData() {}

    /** 重设书籍管理状态 */
    private void resetBookManagerLayout() {
        mDelBookMap.clear();
        tvDelSel.setText("删除所选(0)");
        tvDelSel.setEnabled(false);
        if (isRedact) {
            mBottomLinearLayout.setVisibility(View.GONE);
        }
        isRedact = false;
        bkShelfAdapter.notifyDataSetChanged();
    }

    /** 重新设置标题栏 */
    private void restBookShelfTopTitle(boolean isRestBookShelf) {
        if (isRestBookShelf) {
            mTitle.setTitle("我的书架");
            mTitle.setStyle(true, true);
            mTitle.showRight();
            // 处理显示红点(根据显示条件决定是是否显示)
            mTitle.handleBookShelfMoreRedDot();
        } else {
            mTitle.setTitle("书籍管理");
            mTitle.setStyle(false, false);
            // 暂时隐藏红点
            mTitle.hideRedPoint();
        }
    }

    private void loadData() {
        UserInfo info = MyAccountManager.getInstance(getApplicationContext());
        if (info != null) {
            liMarkInfos = BookMarkInfoDao.getInstance().getBookShefBookMarkList(info.getUserId());
            bkShelfAdapter.setListData(liMarkInfos);
        }

        // 处理左上红点(当左侧按钮显示状态时处理)
        if (mTitle != null && View.VISIBLE == mTitle.getLeftImageView().getVisibility())
            mTitle.handleBookShelfMoreRedDot();
    }

    /** 初始化删除对话框 */
    private void initBookShelfDelDialog(View v) {
        tvDelTitle = (TextView) v.findViewById(R.id.del_dialog_title);
        tvSelCancel = (TextView) v.findViewById(R.id.view_dialog_bottom_bookshelf_sel_cancel_tv);
        tvDel = (TextView) v.findViewById(R.id.view_dialog_bottom_bookshelf_del_confirm_tv);
        delFileBox = (CheckBox) v.findViewById(R.id.view_dialog_bottom_bookshelf_sel_checkbox);
        tvDelDialogDisInfo = (TextView) v.findViewById(R.id.del_dialog_disInfo);
        tvDel.setOnClickListener(this);
        tvSelCancel.setOnClickListener(this);
        delFileBox.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (delFileBox.isChecked()) {
                    isDelFile = true;
                } else {
                    isDelFile = false;
                }
            }
        });
    }

    /** 显示删除书籍对话框 */
    private void showBookShelfSelDelDialog(String title, int position, String disInfo) {
        if (dialogDel == null) {
            View view = View.inflate(this, R.layout.view_dialog_bottom_bookshelf_del, null);
            dialogDel = new BottomDialog(this, view);
            initBookShelfDelDialog(view);
            view.setOnClickListener(this);
            dialogDel.setOnDismissListener(new OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!isRedact) {
                        mDelBookMap.clear();
                    }
                }
            });
        }

        if (disInfo != null && tvDelDialogDisInfo != null) {
            tvDelDialogDisInfo.setText(disInfo);
        }

        tvDelTitle.setText(title);
        delFileBox.setChecked(true);
        isDelFile = true;
        delFileBox.setVisibility(View.VISIBLE);
        if (position != -1) {
            // -1时为批量删除，checkbox显示。不是-1时是单本删除，判断来源类型
            BookMarkInfo info = liMarkInfos.get(position);
            int type = info.getBookType();
            if (BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK == type) {
                delFileBox.setVisibility(View.GONE);
            }
        }

        dialogDel.show();
    }

    /** 关闭删除书籍对话框 */
    private void hideBookShelfSelDelDialog() {
        if (dialogDel != null) {
            dialogDel.dismiss();
        }
    }

    /**
     * 同步云书签
     * 
     * @param sendData
     */
    private void syncBookMark(String sendData) {
        UserInfo info = MyAccountManager.getInstance(getApplicationContext());
        if (!MyAccountManager.isGuestUser(info)) {
            if (syncListener == null) {
                syncListener = new SyncBookMarksListener(this);
            }
            SyncBookMarks
                    .syncBookMarks(ShuqiApplication.getContext(), info, syncListener, sendData);
        }
    }

    // 检查更新
    private void checkUpdate() {
        if (checkUpdateListener == null) {
            checkUpdateListener = new CheckUpdateBookMarksListener(this);
        }
        CheckBookMarkUpdate.getInstance().checkBookMarksUpdate(ShuqiApplication.getContext(),
                checkUpdateListener);
    }

    // 从数据库重新读取一次数据
    private void refreshData() {
        ShuqiApplication.getApplicationHandler().post(new Runnable() {

            @Override
            public void run() {
                loadData();
            }
        });

    }

    private void showNetWorkDialog(final BookMarkInfo info) {
        if (mNetworkDialog == null) {
            View view = getLayoutInflater().inflate(R.layout.view_dialog_network, null);
            view.findViewById(R.id.dialog_cancel_tv).setOnClickListener(this);
            mNetWorkConfirmView = view.findViewById(R.id.dialog_confirm_tv);
            mNetworkDialog = new Dialog(this, R.style.net_dialog);
            LayoutParams params =
                    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            mNetworkDialog.addContentView(view, params);
            mNetworkDialog.setCanceledOnTouchOutside(true);
        }
        if (mNetWorkConfirmView != null) {
            mNetWorkConfirmView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    hideNetWorkDialog();
                    NetNotify.getInstance().changeNotifyState(NetNotify.DOWNLOAD_BOOK_SHELF);
                    downloadBook(info);
                }
            });
        }
        mNetworkDialog.show();
    }

    /** 隐藏网络提示的下载框 */
    private void hideNetWorkDialog() {
        if (mNetworkDialog != null && mNetworkDialog.isShowing()) {
            mNetworkDialog.dismiss();
        }
    }

    /** 判断是否需要显示网络提示的下载框 */
    private boolean isShowNetWorkDialog() {
        boolean isNoWifi =
                NetNotify.getInstance().isNeedNotifyNoWifi(NetNotify.DOWNLOAD_BOOK_SHELF);
        Log4an.e("yjd", "isNoWifi=" + isNoWifi);
        return isNoWifi;
    }

    private void gotoBookSquare() {
        MainActivityGroup.showFromBookShelf(BookShelfActivity.this,
                MainActivityGroup.PAGE_POSITION_BOOKSEARCH, true);
    }

    private void gotoBookShelfFileMangement() {
        ShuqiApplication.getApplicationHandler().postDelayed(new Runnable() {
            public void run() {
                Intent intent =
                        new Intent(BookShelfActivity.this, BookShelfFileMangementAcitvity.class);
                ActivityManager.getInstance().startNextActivity(intent, BookShelfActivity.this);
            }
        }, 200);
    }

    private void gotoWifi() {
        ShuqiApplication.getApplicationHandler().postDelayed(new Runnable() {
            public void run() {
                Intent intent = new Intent(BookShelfActivity.this, FTPTransferActivity.class);
                ActivityManager.getInstance().startNextActivity(intent, BookShelfActivity.this);
            }
        }, 200);
    }

    private void gotoBookDownload() {
        ShuqiApplication.getApplicationHandler().post(new Runnable() {
            public void run() {
                BookDownloadActivity.show(BookShelfActivity.this);
            }
        });
    }

    private void gotoFeedBack() {
        ShuqiApplication.getApplicationHandler().post(new Runnable() {
            public void run() {
                Intent intent = new Intent(BookShelfActivity.this, FeedBackActivity.class);
                ActivityManager.getInstance().startNextActivity(intent, BookShelfActivity.this);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_right: // 点图片进书城
            {
                hideAddBookDialog();
                gotoBookSquare();
                StatisticsUtils.onEvent(BookShelfActivity.this,
                        StatisticsEventID.BOOKSHELF_TO_BOOKSQUARE);
            }
                break;
            case R.id.item_bookshelf_hotbookrecommend_tv: // 热书推荐
            {
                hideAddBookDialog();
                ShuqiApplication.getApplicationHandler().postDelayed(new Runnable() {
                    public void run() {
                        MainActivityGroup.showFromBookShelf(BookShelfActivity.this,
                                MainActivityGroup.PAGE_POSITION_BOOKSEARCH, true);
                    }
                }, 200);
                StatisticsUtils.onEvent(BookShelfActivity.this,
                        StatisticsEventID.BOOKSHELF_HOT_BOOK);
            }
                break;
            case R.id.title_left:// 更多功能
            {
                showPopMoreDialog();
                StatisticsUtils.onEvent(BookShelfActivity.this,
                        StatisticsEventID.BOOKSHELF_CONTINUE_DOWNLOAD_BOOK);
            }
                break;
            case R.id.item_bookshelf_feedback_tv:// 意见反馈
            {
                hidePopMoreDialog();
                gotoFeedBack();
                StatisticsUtils.onEvent(BookShelfActivity.this,
                        StatisticsEventID.BOOKSHELF_FEEDBACK);
            }
                break;
            case R.id.item_bookshelf_account_tv:// 个人中心
            {
                hidePopMoreDialog();
                CheckUserListener listener = new CheckUserListener() {
                    @Override
                    public void onPassed() {
                        AccountActivity.open(BookShelfActivity.this, true);
                        RedDotProvider.getInstance().hideRedDot(
                                VersionShowEnum.personal_center_red_dot);
                    }
                };
                CheckUser.checkUserStateBeforeJump(BookShelfActivity.this, listener);
                StatisticsUtils.onEvent(BookShelfActivity.this,
                        StatisticsEventID.BOOKSHELF_LONGPRESS_BOOK);
            }
                break;
            case R.id.item_bookshelf_bookManagement_tv:// 书籍管理
            {
                hidePopMoreDialog();
                if (liMarkInfos != null && liMarkInfos.size() == 0) {
                    Toast.makeText(BookShelfActivity.this,
                            getResources().getString(R.string.shelf_no_book_toast),
                            Toast.LENGTH_SHORT).show();
                    hidePopMoreDialog();
                    return;
                }
                if (liMarkInfos != null && liMarkInfos.size() > 0
                        && mBottomLinearLayout.getVisibility() != View.VISIBLE) {
                    isRedact = true;
                    restBookShelfTopTitle(false);
                    if (bkShelfAdapter != null) {
                        mBottomLinearLayout.setVisibility(View.VISIBLE);
                        bkShelfAdapter.notifyDataSetChanged();
                    }
                }

                if (mTitle != null) {
                    mTitle.hideRedPoint();
                    mTitle.hideRight();
                }

                StatisticsUtils.onEvent(BookShelfActivity.this,
                        StatisticsEventID.BOOKSHELF_BOOK_MANAGE);
            }
                break;
            case R.id.item_bookshelf_localLoad_tv:// 导入本地
            {
                hidePopMoreDialog();
                gotoBookShelfFileMangement();
                StatisticsUtils.onEvent(BookShelfActivity.this,
                        StatisticsEventID.BOOKSHELF_LOCAL_LOAD);
            }
                break;
            case R.id.item_bookshelf_localLoad_tv1: {
                hideAddBookDialog();
                gotoBookShelfFileMangement();
                StatisticsUtils.onEvent(BookShelfActivity.this, StatisticsEventID.BOOKSHELF_LOCAL);
            }
                break;

            case R.id.item_bookshelf_mybookbag_tv:// 我的书包
                MyBookBagActivity.show(this);
                RedDotProvider.getInstance().hideRedDot(VersionShowEnum.my_book_bag_red_dot);
                hidePopMoreDialog();
                StatisticsUtils.onEvent(BookShelfActivity.this,
                        StatisticsEventID.BOOKSHELF_MENU_CLICKBAG);
                break;
            case R.id.item_bookshelf_wifiTransfer_tv1: {
                hideAddBookDialog();
                gotoWifi();
                StatisticsUtils.onEvent(BookShelfActivity.this,
                        StatisticsEventID.BOOKSHELF_WIFI_LOAD);
            }
                break;
            case R.id.item_bookshelf_offlineManagement_tv: {// 离线书籍管理
                hidePopMoreDialog();
                gotoBookDownload();
                FunctionsSwitch.setShowDownloadHint(this, false);
                StatisticsUtils.onEvent(BookShelfActivity.this,
                        StatisticsEventID.BOOKSHELF_OFFLINE_MANAGE);
            }
                break;
            case R.id.shelf_cancel_tv:// 书籍管理取消
                resetBookManagerLayout();
                restBookShelfTopTitle(true);

                break;
            case R.id.shelf_del_sel_tv:// 书籍管理删除
                showBookShelfSelDelDialog("删除书籍", -1, "确定删除所选的书籍吗？");
                break;
            case R.id.view_dialog_bottom_bookshelf_sel_cancel_tv:// 删除对话框取消
                restBookShelfTopTitle(true);
                dialogDel.dismiss();
                resetBookManagerLayout();
                break;
            case R.id.view_dialog_bottom_bookshelf_del_confirm_tv:// 删除对话框确定
                restBookShelfTopTitle(true);
                clickDelBookMarkButton();
                hideBookShelfSelDelDialog();
                resetBookManagerLayout();
                break;
            case R.id.dialog_cancel_tv:
                hideNetWorkDialog();
                break;
            case R.id.dialog_confirm_tv:
                hideNetWorkDialog();
                NetNotify.getInstance().changeNotifyState(NetNotify.DOWNLOAD_BOOK_OFFLINE);
                break;
        }
    }

    /** addbook对话框 */
    private void hideAddBookDialog() {
        ShuqiApplication.getApplicationHandler().post(new Runnable() {
            public void run() {
                if (dialogAddBook != null && dialogAddBook.isShowing()) {
                    dialogAddBook.dismiss();
                }
            }
        });
    }

    /** addbook对话框 */
    private void showAddBookDialog() {
        StatisticsUtils.onEvent(BookShelfActivity.this, StatisticsEventID.BOOKSHELF_ADD);
        if (dialogAddBook == null) {
            View view = View.inflate(this, R.layout.view_dialog_bottom_bookshelf_addbook, null);
            dialogAddBook = new BottomDialog(this, view);
            initAddBookDialog(view);
            view.setOnClickListener(this);
        }
        dialogAddBook.show();
    }

    /** 初始化书架addbook */
    private void initAddBookDialog(View v) {

        tvHotBookRecommen =
                (RelativeLayout) v.findViewById(R.id.item_bookshelf_hotbookrecommend_tv);
        tvLocalLoad1 = (RelativeLayout) v.findViewById(R.id.item_bookshelf_localLoad_tv1);
        tvWifiTransfer1 = (RelativeLayout) v.findViewById(R.id.item_bookshelf_wifiTransfer_tv1);

        tvHotBookRecommen.setOnClickListener(this);
        tvLocalLoad1.setOnClickListener(this);
        tvWifiTransfer1.setOnClickListener(this);
    }

    /** 切换popwindow的隐藏，显示 */
    private void changePopMoreDialog() {
        if (isRedact) {
            return;
        }
        if (popDialogMore != null && popDialogMore.isShowing()) {
            // pop显示则无法响应activity的menu键，所以此处无用
            popDialogMore.dismiss();
        } else {
            showPopMoreDialog();
        }
    }

    /** popwindow */
    private void hidePopMoreDialog() {
        ShuqiApplication.getApplicationHandler().post(new Runnable() {
            public void run() {
                if (popDialogMore != null && popDialogMore.isShowing()) {
                    popDialogMore.dismiss();
                }
            }
        });
    }

    /** popwindow */
    private void showPopMoreDialog() {

        if (popDialogMore == null) {
            View view = View.inflate(this, R.layout.view_popwindow_bookshelf_more, null);
            popDialogMore =
                    new CustomPopupWindow(this, view, LinearLayout.LayoutParams.WRAP_CONTENT);
            initPopMoreDialog(view);
            view.setOnClickListener(this);
        }
        // 书包入口初始化
        boolean hasBookBag = BookBagDao.getInstance().isHasDownLoadedBookBag();
        tvMyBookBag_line.setVisibility(hasBookBag ? View.VISIBLE : View.GONE);
        tvMyBookBag.setVisibility(hasBookBag ? View.VISIBLE : View.GONE);
        tvMyBookBag.setOnClickListener(hasBookBag ? this : null);

        // 书包红点控制
        if (View.VISIBLE == tvMyBookBag.getVisibility()) {

            boolean myBookBagRedDotIsShow =
                    RedDotProvider.getInstance().isShowRedDot(VersionShowEnum.my_book_bag_red_dot);
            if (myBookBagRedDotIsShow) {

                tvMyBookBag.setCompoundDrawablesWithIntrinsicBounds(
                        R.drawable.icon_bookshelf_more_bag_selector, 0, R.drawable.red_point, 0);

            } else {

                tvMyBookBag.setCompoundDrawablesWithIntrinsicBounds(
                        R.drawable.icon_bookshelf_more_bag_selector, 0, 0, 0);

            }
        }

        // 个人中心红点控制
        if (View.VISIBLE == tvPersonalCenter.getVisibility()) {

            boolean show =
                    RedDotProvider.getInstance().isShowRedDot(
                            VersionShowEnum.personal_center_red_dot);

            boolean newPullVersion =
                    RedDotProvider.getInstance().isShowRedDot(
                            VersionShowEnum.new_pull_version_red_dot);

            if (show) {

                tvPersonalCenter.setCompoundDrawablesWithIntrinsicBounds(
                        R.drawable.bg_personal_center_selector, 0, R.drawable.red_point, 0);

            } else if (newPullVersion && SharedPreferenceUtil.isSoftUpdate(this)) {

                tvPersonalCenter.setCompoundDrawablesWithIntrinsicBounds(
                        R.drawable.bg_personal_center_selector, 0, R.drawable.red_point, 0);

            } else {

                tvPersonalCenter.setCompoundDrawablesWithIntrinsicBounds(
                        R.drawable.bg_personal_center_selector, 0, 0, 0);

            }
        }


        if (FunctionsSwitch.isShowDownloadHint(this)) {
            tvOfflineMangement.setCompoundDrawablesWithIntrinsicBounds(
                    R.drawable.bg_offlinemanagement_selector, 0, R.drawable.red_point, 0);
        } else {
            tvOfflineMangement.setCompoundDrawablesWithIntrinsicBounds(
                    R.drawable.bg_offlinemanagement_selector, 0, 0, 0);
        }
        popDialogMore.showRight(mTitle.leftImageView);

        if (viewHelp == null || !viewHelp.isShowing()) {// 当前没有显示帮助界面时执行
            View parentView = findViewById(R.id.bookshelf_root);
            int resId = R.layout.view_help_bookshelf_more;
            VersionShowEnum vShowEnum = VersionShowEnum.view_help_bookshelf_more;

            // 显示更多使用帮助
            viewHelp =
                    ViewHelpProvider.getInstance().handle(this, vShowEnum,
                            ViewHelpHandleType.layout, parentView, resId);
        }
    }

    /** 初始化书架pop */
    private void initPopMoreDialog(View v) {
        // 书籍管理在pop中，初始化
        mBottomLinearLayout = (LinearLayout) findViewById(R.id.bookshelf_bottom_lin);
        tvPersonalCenter = (TextView) v.findViewById(R.id.item_bookshelf_account_tv);
        tvFeedBack = (TextView) v.findViewById(R.id.item_bookshelf_feedback_tv);
        tvBookManagement = (TextView) v.findViewById(R.id.item_bookshelf_bookManagement_tv);
        tvLocalLoad = (TextView) v.findViewById(R.id.item_bookshelf_localLoad_tv);
        tvOfflineMangement = (TextView) v.findViewById(R.id.item_bookshelf_offlineManagement_tv);
        tvMyBookBag = (TextView) v.findViewById(R.id.item_bookshelf_mybookbag_tv);
        tvMyBookBag_line = v.findViewById(R.id.item_bookshelf_mybookbag_line);

        tvFeedBack.setOnClickListener(this);
        tvPersonalCenter.setOnClickListener(this);
        tvBookManagement.setOnClickListener(this);
        tvLocalLoad.setOnClickListener(this);
        tvOfflineMangement.setOnClickListener(this);

    }

    /** 点击确认删除按钮 */
    private void clickDelBookMarkButton() {
        // 遍历map
        Iterator<Entry<String, BookMarkInfo>> it = mDelBookMap.entrySet().iterator();
        final List<BookMarkInfo> markInfos = new ArrayList<BookMarkInfo>();
        while (it.hasNext()) {
            Entry<String, BookMarkInfo> entry = (Entry<String, BookMarkInfo>) it.next();
            markInfos.add(entry.getValue());
            // 删除内存
            if (liMarkInfos != null) {
                liMarkInfos.remove(entry.getValue());
            }
            // markInfos.add(entry.getValue());
        }

        Runnable r = new Runnable() {
            @Override
            public void run() {
                BookMarkManager.getInstance().delBookMarks(markInfos, isDelFile);
            }
        };
        new Thread(r).start();
        // 更新UI
        bkShelfAdapter.setListData(liMarkInfos);
        showMsg("删除成功");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
            changePopMoreDialog();
            StatisticsUtils.onEvent(BookShelfActivity.this,
                    StatisticsEventID.BOOKSHELF_MAORE_PHYSICAL_MENU);
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (isRedact) {// 编辑状态
                restBookShelfTopTitle(true);
                resetBookManagerLayout();
                return true;
            } else {
                if (isCanQuit) {
                    if (Util.isNetworkConnected(this)) {
                        Log4an.i("yjd", "syncBookMark in the app is exit.");
                        syncBookMark("no");
                    }
                    // FreeBookDownloadManager.getInstance().finishTask();

                    TxtDownLoadManager.getInstance().finishTask();


                    new Thread() {
                        public synchronized void run() {
                            SharedPreferences sp =
                                    getSharedPreferences("tempcatalog", MODE_PRIVATE);
                            Map map = sp.getAll();
                            Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
                            while (it.hasNext()) {
                                Map.Entry<String, String> entry = it.next();
                                String[] key = entry.getKey().split("##");
                                String cid = entry.getValue();
                                File dir = null;
                                // bookId##userId##sourceId
                                if (key.length < 3) {
                                    // TODO 关闭软件时 清除缓存目录对应的表
                                    BookCataLogDao.getInstance().deleteBookCatalogByBookId(key[0],
                                            null, key[1]);
                                    // TODO 关闭软件时 删除wifi下缓存的文件
                                    dir =
                                            new File(Config.DEFAULT_SHUQI_CHAPTER_CACHE_PATH
                                                    + key[1] + "/" + key[0] + "/");
                                } else {
                                    BookCataLogDao.getInstance().deleteBookCatalogByBookId(key[0],
                                            key[2], key[1]);
                                    // TODO 关闭软件时 删除wifi下缓存的文件
                                    dir =
                                            new File(Config.DEFAULT_YISOU_CHAPTER_CACHE_PATH
                                                    + key[1] + "/" + key[2] + "/" + key[0] + "/");
                                }


                                if (!dir.exists()) {
                                    dir.mkdirs();
                                }
                                File file =
                                        new File(dir, cid + DownLoadBookManager.CHAPTER_FILE_SUFFIX);
                                if (file.exists()) {
                                    try {
                                        if (file.isDirectory()) {
                                            Util.forceDelDir(file);
                                        } else {
                                            file.delete();
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                        };
                    }.start();
                    finish();// 退出软件
                } else {
                    Toast.makeText(getApplicationContext(),
                            getResources().getString(R.string.app_exit), Toast.LENGTH_SHORT).show();
                    quitCountDown();
                }
                return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 此方法用于将用户点击的下载书籍在书签中提前
     */
    private void checkAndUpdateDownloadBookMark(final BookMarkInfo info) {
        if (liMarkInfos != null && liMarkInfos.size() > 0 && liMarkInfos.get(0) != info) {
            liMarkInfos.remove(info);
            liMarkInfos.add(0, info);
            bkShelfAdapter.setListData(liMarkInfos);
            BookMarkInfoDao.getInstance().saveOrUpdateBookMark(info);
        }
    }

    /** 主动暂停标识 1,暂停；2,正在下载 */
    private int pauseTag;// 8.0.1 主动暂停/开始时，不提示toast
    private DownloadInfo doInfo = null;

    private void jumpBookContentActivity(final BookMarkInfo info) {
        if (isRedact) {
            // 编辑状态
            if (mDelBookMap.containsKey(info.getUniqueKey())) {
                mDelBookMap.remove(info.getUniqueKey());
            } else {
                mDelBookMap.put(info.getUniqueKey(), info);
            }

            // 更新底部Dialog UI
            tvDelSel.setText("删除所选(" + mDelBookMap.size() + ")");
            tvDelSel.setEnabled(mDelBookMap.size() > 0);

            // girdView的item的UI
            bkShelfAdapter.notifyDataSetChanged();
            // bkShelfAdapter.updateDelUI(info.getBookMarkId(), isDel);
            return;
        }


        info.setUpdateFlag(BookMarkInfo.UPDATE_FLAG_NOT);
        Log4an.e("yjd", "点击Item getBookId=" + info.getBookId());
        if (!TextUtils.isEmpty(info.getBookId())) {
            // 正常处理点击事件
            doInfo =
                    DownLoadShuqiBook.getInstace()
                            .getDownBookState(
                                    MyAccountManager.getInstance(ShuqiApplication.getContext())
                                            .getUserId(), info.getBookId());

        } else {
            doInfo = null;
        }
        Log4an.e("yjd", "点击Item doInfo is null=" + (doInfo == null));
        if (doInfo != null) {
            if (mDownWaitState == DownloadStatus.STATE_WAIT) {
                Log4an.e(TAG, "When handling a wait state, click is invalid");
                return;
            }
            int downLoadState = doInfo.getDownloadStatus();
            Log4an.e("yjd", "downLoadState=" + downLoadState);
            boolean isDown = info.isNeedDown(downLoadState);
            Log4an.e("yjd", "isDown=" + isDown);
            if (isDown) {
                if (downLoadState == DownloadStatus.STATE_WAIT) {
                    Log4an.e(TAG, "downLoadState == DownloadStatus.STATE_WAIT");
                    return;
                }
                if (downLoadState == DownloadStatus.STATE_STOP) {
                    // checkAndUpdateDownloadBookMark(info);
                }
                if (downLoadState == DownloadStatus.STATE_RUN
                        || downLoadState == DownloadStatus.STATE_UNZIP) {
                    pauseTag = 1;
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {
                            bkShelfAdapter.updateDownloadUI(info.getBookId(),
                                    DownloadStatus.STATE_STOP, doInfo.getDownloadPercent());
                        }
                    };
                    ShuqiApplication.getApplicationHandler().post(r);
                    DownLoadShuqiBook.getInstace()
                            .stopDownBook(
                                    MyAccountManager.getInstance(ShuqiApplication.getContext())
                                            .getUserId(), info.getBookId());
                    return;
                }
                boolean isShow = isShowNetWorkDialog();
                Log4an.e("yjd", "isShow=" + isShow);
                if (!isShow) {
                    downloadBook(info);
                } else {
                    int changeNet = info.isNeedDownChangeNet(doInfo.getDownloadStatus());
                    Log4an.e("yjd", "changeNet=" + changeNet);
                    // if (changeNet == DownConstant.STATE_ERROR) {
                    showNetWorkDialog(info);
                    // }
                }
            } else {
                gotoReadPage(info);
                checkAndUpdateDownloadBookMark(info);
                StatisticsUtils.onEvent(BookShelfActivity.this,
                        StatisticsEventID.BOOKSHELF_READBOOK);
            }
        } else {
            gotoReadPage(info);
            StatisticsUtils.onEvent(BookShelfActivity.this, StatisticsEventID.BOOKSHELF_READBOOK);
        }
    }


    /**
     * 下载书籍
     * 
     * @param info
     */
    private void downloadBook(BookMarkInfo info) {
        if (!Util.isCanUseSdCard()) {
            showMsg(TxtDownLoadManager.NO_SDCARD);
            return;
        }
        if (!Util.isNetworkConnected(this)) {
            showMsg(getResources().getString(R.string.net_error_text));
            return;
        }
        UserInfo userInfo = MyAccountManager.getInstance(ShuqiApplication.getContext());
        if (userInfo != null && !TextUtils.isEmpty(userInfo.getUserId())) {
            pauseTag = 2;
            Log4an.i("yjd", "开始下载uid=" + userInfo.getUserId() + ",bid=" + info.getBookId());
            DownLoadShuqiBook.getInstace().startDownBook(userInfo.getUserId(), info.getBookId(),
                    new StartDownBookListener() {
                        @Override
                        public void onFinish(boolean isSuccess, String message) {
                            Log4an.i("yjd", "isSuccess=" + isSuccess + ",message=" + message);
                            if (!isSuccess) {
                                showMsg(message);
                            }
                        }
                    });
        }
    }

    /**
     * 跳转到阅读页
     * 
     * @param info
     */
    private void gotoReadPage(BookMarkInfo info) {
        if (info == null) {
            return;
        }
        int type = info.getBookType();
        if (BookMarkInfo.TYPE_LOCAL_BOOKMARK == type || BookMarkInfo.TYPE_NEW_PAY_BOOKMARK == type
                || BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK == type
                || BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK == type
                || BookMarkInfo.TYPE_OLD_BAG_BOOKMARK == type) {
            // 本地 阅读页
            EnterBookContent.jumpToBookContentByBookMark(BookShelfActivity.this, info,
                    BookContentActivity.INTENT_REQUEST_CODE_BOOKSHLEF);
        } else if (BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK == type) {
            // 网页
            String url =
                    Urls.getWebBookReadUrl(ShuqiApplication.getContext(), info.getBookId(),
                            info.getSourceId(), info.getChapterId());
            WebKitActivity.openWebkit(this, url);
        } else if (BookMarkInfo.TYPE_OLD_WEB_BOOKMARK == type) {
            // 网页
            String url = null;
            if (!TextUtils.isEmpty(info.getFilePath())) {
                String cid = MyUrlTools.getChapterIdFromWebBookMarkUrl(info.getFilePath());
                if (TextUtils.isEmpty(cid)) {
                    url = info.getFilePath();
                } else {
                    url =
                            Urls.getWebBookReadUrl(ShuqiApplication.getContext(), info.getBookId(),
                                    info.getSourceId(), info.getChapterId());
                }
                WebKitActivity.openWebkit(this, url);
            }
        }
    }



    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        DownLoadShuqiBook.getInstace().registerDownStateListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解注册
        DownLoadShuqiBook.getInstace().unRegisterDownStateListener(this);
        if (liMarkInfos != null) {
            liMarkInfos.clear();
            liMarkInfos = null;
        }
        bkShelfAdapter.onDestroy();

        if (mDelBookMap != null) {
            mDelBookMap.clear();
            mDelBookMap = null;
        }

        hidePopMoreDialog();

        hideAddBookDialog();

        hideBookShelfSelDelDialog();

        hideNetWorkDialog();
        DownLoadShuqiBook.getInstace().clearAllCache();
        ShuqiApplication.onExit();
    }

    private boolean isNetWorkAvailable() {
        int netType = HttpFactory.getApnType(this);
        return netType != HttpFactory.NOT_EXIST;
    }

    public static class SyncBookMarksListener implements SyncBookMarksResultToUILinstener {
        private WeakReference<BookShelfActivity> ref;

        public SyncBookMarksListener(BookShelfActivity activity) {
            ref = new WeakReference<BookShelfActivity>(activity);
        }

        @Override
        public void onResult(boolean isSuccess, List<BookMarkInfo> markList) {
            if (ref == null || ref.get() == null || ref.get().isFinishing()) {
                return;
            }

            if (isSuccess) {
                ref.get().refreshData();
            }
            // 检查更新
            ref.get().checkUpdate();

        }
    }

    public static class CheckUpdateBookMarksListener implements CheckBookMarkUpdateLinstener {
        private WeakReference<BookShelfActivity> ref;

        public CheckUpdateBookMarksListener(BookShelfActivity activity) {
            ref = new WeakReference<BookShelfActivity>(activity);
        }

        @Override
        public void onFinish(boolean isAllSuccess, int resultType, List<CheckBookUpdateInfo> list) {
            if (ref == null || ref.get() == null || ref.get().isFinishing()) {
                return;
            }

            if (resultType == CheckBookMarkUpdate.TYPE_CHECKRESULT_HASUPDATE) {
                ref.get().refreshData();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case BookContentActivity.INTENT_REQUEST_CODE_BOOKSHLEF:
                if (resultCode == Activity.RESULT_OK) {
                    final int bookType =
                            data.getIntExtra(BookContentActivity.INTENT_RESULT_BOOKSELF_BOOKTYPE,
                                    -1);
                    final String bookName =
                            data.getStringExtra(BookContentActivity.INTENT_RESULT_BOOKSELF_BOOKNAME);

                    final String filePath =
                            data.getStringExtra(BookContentActivity.INTENT_RESULT_BOOKSELF_FILEPATH);

                    final String bookId =
                            data.getStringExtra(BookContentActivity.INTENT_RESULT_BOOKSELF_BOOKID);

                    showReadErrorDialog(bookName, bookType, filePath, bookId);
                }
                break;
        }
    }

    private void showReadErrorDialog(String bookName, int bookType, String filePath, String bookId) {
        Log.d(TAG, "bookName : " + bookName + " bookType : " + bookType + " filePath : " + filePath
                + " bookId : " + bookId);
        if (liMarkInfos == null || liMarkInfos.size() == 0) {
            return;
        }
        int position = findBookPositionInMarkInfos(bookId, filePath);
        if (position >= 0) {
            BookMarkInfo info = liMarkInfos.get(position);
            mDelBookMap.put(info.getUniqueKey(), info);
            showBookShelfSelDelDialog("书籍格式有误", position, "书籍格式有误无法阅读，是否删除该书籍？");
        }
    }

    private int findBookPositionInMarkInfos(String bookId, String filePath) {
        int position = -1;
        if (liMarkInfos != null || liMarkInfos.size() > 0) {

            int markInfoSize = liMarkInfos.size();
            for (int i = 0; i < markInfoSize; i++) {
                BookMarkInfo info = liMarkInfos.get(i);

                if (info != null) {
                    if (bookId != null) {
                        if (bookId.equals(info.getBookId())) {
                            position = i;
                            break;
                        }

                    }
                    if (filePath != null) {
                        if (filePath.equals(info.getFilePath())) {
                            position = i;
                            break;
                        }
                    }
                }
            }
        }

        return position;
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
        position = position - 3;
        if ((liMarkInfos == null || liMarkInfos.size() == 0) && (position == 0)) {
            showAddBookDialog();
            return;
        } else if (position == liMarkInfos.size()) {
            if (!isRedact) {
                showAddBookDialog();
            }
            return;
        }

        if (position > liMarkInfos.size() || position < 0) {
            return;
        }

        final BookMarkInfo info = liMarkInfos.get(position);
        // 未验证账户拦截，已取消
        jumpBookContentActivity(info);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3) {
        position = position - 3;
        if (liMarkInfos == null || liMarkInfos.size() == 0 || position >= liMarkInfos.size()
                || isRedact || position < 0) {

            // 更多按钮不处理
            return false;
        }
        BookMarkInfo info = liMarkInfos.get(position);
        mDelBookMap.put(info.getUniqueKey(), info);
        StatisticsUtils.onEvent(BookShelfActivity.this, StatisticsEventID.BOOKSHELF_ADDBOOK);
        // showBookShelfSelDelDialog(info.getBookName(), position, null);
        showBookShelfSelDelDialog(info.getBookName(), position, "确定删除所选的书籍吗？");
        return true;
    }

    // ========================以下是8.0.1新增代码===========================

    /** 书旗新版本检查更新 */
    private void checkShuqiUpdate() {
        final SoftUpdateInfo info = SoftCofigManager.getInstance().getUpdateInfo();

        if (info != null && StringUtils.isNotBlank(info.getPullVersion())) {
            int oldVersion = Integer.valueOf(Config.VERSION_INFO);
            int newPullVersion = Integer.valueOf(info.getPullVersion());

            // 手动更新
            if (oldVersion < newPullVersion) {
                SharedPreferenceUtil.setSoftUpdate(this, true);
            }else{
                SharedPreferenceUtil.setSoftUpdate(this, false);
            }
        }


        if (info != null && StringUtils.isNotBlank(info.getPushVersion())) {

            int oldVersion = Integer.valueOf(Config.VERSION_INFO);
            int newVersion = Integer.valueOf(info.getPushVersion());
            int noPromptPushVersion = SharedPreferenceUtil.getNoPromptPushVersion(this);

            // 自动提示更新
            if (oldVersion < newVersion && newVersion != noPromptPushVersion) {
                dialog =
                        new UpdateDialog(this, R.style.UpdateDialog, "更新提示", info.getPushIntro(),
                                newVersion, "取消", "立即更新");
                dialog.setRightBtnOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        UpdateService.startDownLoadAppService(ShuqiApplication.getContext(),
                                info.getPushUrl());
                        dialog.cancel();
                    }
                });

                mHandler.sendEmptyMessageDelayed(SHOW_UPDATE, 1000);
            }

        }
    }

    public static void show(Context context, boolean isClearTop) {
        Intent intent = new Intent(context, BookShelfActivity.class);
        if (isClearTop) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }
        context.startActivity(intent);
        if (context instanceof Activity) {
            ((Activity) context).overridePendingTransition(R.anim.push_left_in,
                    R.anim.push_right_out);
        }
    }

    public static void showFromMainActivityGroup(Context context, boolean isClearTop) {
        Intent intent = new Intent(context, BookShelfActivity.class);
        if (isClearTop) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }
        context.startActivity(intent);
        if (context instanceof Activity) {
            ((Activity) context).overridePendingTransition(R.anim.push_left_in,
                    R.anim.push_right_out);
        }
    }

    public static void showFromLoading(Context context, boolean isClearTop) {
        Intent intent = new Intent(context, BookShelfActivity.class);
        if (isClearTop) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }
        dealIntent(((Activity) context), intent);
        context.startActivity(intent);
        if (context instanceof Activity) {
            ((Activity) context).overridePendingTransition(R.anim.push_right_in,
                    R.anim.push_left_out);
        }
    }

    /** 由文件跳入处理intent */
    public static void dealIntent(Activity activity, Intent intent2BookShelf) {
        Intent intent = activity.getIntent();

        if (intent == null) {
            return;
        }

        try {
            Uri uri = (Uri) intent.getData();
            if (uri != null) {
                String path = uri.getPath().toLowerCase().trim();
                if (path.endsWith(".txt") || path.endsWith(".sqb.zip") || path.endsWith(".sqd.zip")
                        || path.endsWith(".epub") || path.endsWith(".umd")) {

                    File file = new File(path);
                    if (file.exists()) {
                        intent2BookShelf.putExtra(INTENT_FROM_FILE, path);
                    } else {
                        Toast.makeText(activity, "关联打开文件不存在,请检查路径.", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(activity, "关联打开非支持格式", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void jumpToBookContent() {
        if (getIntent() != null) {
            String filepath = getIntent().getStringExtra(INTENT_FROM_FILE);
            if (!TextUtils.isEmpty(filepath)) {
                Log4an.e("MainActivityGroup", filepath);
                EnterBookContent.jumpToBookContentByFilePath(this, filepath, -1);
            }
        }
    }

    // private void jumpToNewGuide() {
    // Intent intent = getIntent();
    // if (intent != null && intent.getBooleanExtra(INTENT_SHOWGUIDE, false)
    // && !FunctionsSwitch.isShowedNewbieGuide(this)) {
    // NewbieGuideActivity.show(this, true);
    // FunctionsSwitch.showedNewbieGuide(this, true);
    // }
    // }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        jumpToBookContent();
    }

    /*** 退出倒计时 */
    private void quitCountDown() {
        MyTask.runInBackground(new Runnable() {
            @Override
            public void run() {
                try {
                    isCanQuit = true;
                    Thread.sleep(5000);
                    isCanQuit = false;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, true);
    }

    /** 等待状态点击无效 */
    private int mDownWaitState = -1;

    @Override
    public void updateDownState(String uid, final String bid, final int state, final float percent) {
        // Log4an.i(TAG, "@Override  updateDownState state=" + state + ",percent=" + percent);
        mDownWaitState = state;
        Runnable r = new Runnable() {
            @Override
            public void run() {
                switch (state) {
                    case DownloadStatus.STATE_WAIT:
                        break;
                    case DownloadStatus.STATE_STOP:
                        if (pauseTag == 2) {
                            if (!isNetWorkAvailable()) {
                                showMsg(getResources().getString(R.string.net_error_text));
                            } else {
                                showMsg("下载异常，请重试");
                            }
                        }
                        break;
                    case DownloadStatus.STATE_UNZIP_STOP:
                        showMsg("解压失败");
                        break;
                    case DownloadStatus.STATE_ERR_CONN:
                    case DownloadStatus.STATE_ERR_DB:
                        showMsg(getResources().getString(R.string.net_error_text));
                        break;
                    case DownloadStatus.STATE_DONE:
                        showMsg("下载成功");
                        break;
                    default:
                        break;
                }
                bkShelfAdapter.updateDownloadUI(bid, state, percent);
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);
    }

    // ========================以上是8.0.1新增代码===========================
}
